import React, { useRef, useEffect, useState } from 'react';

export function usePrevious<T>(value: T) {
  const ref = useRef<T>();

  // 将当前值存入ref.current
  useEffect(() => {
    ref.current = value;
  }, [value]);

  return ref.current as T;
}

// usePrevious
function usePreviousDemo() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  console.log('Current count:', count);
  console.log('Previous count:', prevCount);

  // todo prevCount is undefined
  if (prevCount === undefined) {
    console.log('prevCount is undefined');
    debugger;
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(prevCount + 1)}>Increment</button>
    </div>
  );
}
